package server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 * Rappresenta il client
 * 
 * @author Java e Le Storie Tese
 *
 */
public class Client implements Runnable, IClient {

	private Socket socket;
	private IServerMediator mediator;
	
	private BufferedWriter bw;
	private BufferedReader br;
	
	private boolean check=true;
	
	public Client(Socket s, IServerMediator mediator) {
		super();
		this.socket = s;
		this.mediator = mediator;
	
		
		try {
		
			br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF8"));
			bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8"));
			
		}catch(IOException e){
			
			System.err.println("Errore nella creazione degli stream");
			
		}
	}

	@Override
	public void run() {
		
		String read="";
		
		while(check){
			
			try {
				read=br.readLine();
				
				if(read==null){
					check=false;
				
				}else{
					if(read.substring(0, 1).equalsIgnoreCase("+")){
						
						mediator.sendMsg("** "+read.substring(1,read.length())+" si è appena connesso! **");
						mediator.addNick(socket.getInetAddress().getHostAddress(),read.substring(0,read.length()));
						
					}else{
					
						mediator.sendMsg(read);
					
					}
					
				}
				
			} catch (IOException e) {
				System.err.println("Errore nello stream dati!");
				check=false;
			}
		}
		
		try {
			socket.close();
			
		} catch (IOException e) {
			System.err.println("Errore nella chiusura del socket!");
		}
		
		mediator.rmClient(this);
		
	}
	
	/* (non-Javadoc)
	 * @see server.IClient#sendMessage(java.lang.String)
	 */
	@Override
	public void sendMessage(String msg){
		
		try {
			bw.write(msg +"\n");
			bw.flush();
		} catch (IOException e) {
			System.err.println("Errore nella scrittura dello Stream!");
		
		}
		
	}

	@Override
	public Socket getSocket() {
		return this.socket;
	}
	
	
}
